package com.camemax.dispatch.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

// *********************
// ** @Date: 2021-06-22
// ** @Author: Camemax
// ** @Description: 配单服务 - 配置死信队列 与 重建订单队列（添加死信支持）
// *********************
@Configuration
public class DispatchConfiguration {
    @Autowired
    private RabbitTemplate template;

    // 死信队列
    @Bean
    public FanoutExchange declareDLXFanoutExchange() {
        return new FanoutExchange("dlx-fanout-exchange");
    }

    @Bean
    public Queue declareDLXQueue() {
        return new Queue("dlx-queue", true, false, false, null);
    }

    @Bean
    public Binding declareDLXBindings() {
        return BindingBuilder.bind(declareDLXQueue()).to(declareDLXFanoutExchange());
    }

    // 功能队列
    @Bean
    public Queue declareNewOrderQueue(){
        String ordersQueue = "orders-queue";
        // 实例化RabbitAdmin对象，并根据RabbitTemplate获取对应的Rabbitmq服务
        RabbitAdmin rabbitAdmin = new RabbitAdmin(template);
        // 获取指定队列的信息
        QueueInformation queueInfo = rabbitAdmin.getQueueInfo(ordersQueue);
        // 如果已存在相关队列，则进行删除！ （ ** 生产环境不推荐执行 ** ）
        if ( queueInfo != null ){
            rabbitAdmin.deleteQueue(ordersQueue);
        }
        // 配置死信属性
        HashMap<String, Object> dlxMap = new HashMap<>();
        dlxMap.put("x-dead-letter-exchange", "dlx-fanout-exchange");
        // 重建队列，新队列具有分发死信队列功能
        return new Queue(ordersQueue , true, false, false, dlxMap);
    }

    // 重建队列后的关系绑定
    @Bean
    public FanoutExchange orderExchange() {
        return new FanoutExchange("orders-fanout-exchange", true, false, null);
    }
    @Bean
    public Binding declareNewOrderBindings() {
        return BindingBuilder.bind(declareNewOrderQueue()).to(orderExchange());
    }
}
